package com.employment.security;

import com.employment.entity.User;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.Collections;

/**
 * Spring Security用户详情实现类
 * 
 * @author Employment System
 * @since 1.0.0
 */
@Data
public class UserPrincipal implements UserDetails {

    private Long userId;
    private String username;
    private String password;
    private String email;
    private String phone;
    private Integer userType;
    private Integer status;

    public UserPrincipal(User user) {
        this.userId = user.getUserId();
        this.username = user.getUsername();
        this.password = user.getPassword();
        this.email = user.getEmail();
        this.phone = user.getPhone();
        this.userType = user.getUserType();
        this.status = user.getStatus();
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        // 根据用户类型分配权限
        String role = "ROLE_USER";
        switch (userType) {
            case 1:
                role = "ROLE_JOBSEEKER"; // 求职者
                break;
            case 2:
                role = "ROLE_COMPANY"; // 企业用户
                break;
            case 3:
                role = "ROLE_ADMIN"; // 管理员
                break;
        }
        return Collections.singletonList(new SimpleGrantedAuthority(role));
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return status == 1; // 1表示正常状态
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return status == 1; // 1表示启用状态
    }

    /**
     * 获取用户ID
     */
    public Long getId() {
        return userId;
    }

    /**
     * 判断是否为管理员
     */
    public boolean isAdmin() {
        return userType == 3;
    }

    /**
     * 判断是否为企业用户
     */
    public boolean isCompanyUser() {
        return userType == 2;
    }

    /**
     * 判断是否为求职者
     */
    public boolean isJobSeeker() {
        return userType == 1;
    }
}